<template>
  <div class="ai-chat-container">
    <!-- 聊天窗口 -->
    <div class="ai-chat-widget" v-show="isOpen">
      <div class="chat-header">
        <span class="chat-title">智能客服</span>
        <span class="minimize-btn" @click="toggleChat">-</span>
      </div>
      <div class="chat-messages" ref="messageContainer">
        <div v-for="(msg, index) in messages" 
             :key="index" 
             :class="['message', msg.role === 'user' ? 'user' : 'bot']">
          {{ msg.content }}
        </div>
      </div>
      <div class="chat-input">
        <textarea 
          v-model="userInput"
          placeholder="请输入您的问题..."
          rows="1"
          @keydown.enter.prevent="handleEnter"
        ></textarea>
        <button @click="sendMessage">发送</button>
      </div>
    </div>

    <!-- 启动器按钮 -->
    <div class="chat-launcher" @click="toggleChat" v-show="!isOpen">
      <span class="launcher-icon">💬</span>
    </div>
  </div>
</template>

<script>
export default {
  name: 'AIChatWidget',
  
  data() {
    return {
      isOpen: false,
      userInput: '',
      messages: [
        {
          role: 'assistant',
          content: '您好！我是AI助手，很高兴为您服务。请问有什么可以帮您？'
        }
      ],
      chatHistory: [
        {
          role: 'assistant',
          content: '您好！我是AI助手，很高兴为您服务。请问有什么可以帮您？'
        }
      ],
      apiUrl: 'http://192.168.10.3:11434/api/chat'
    }
  },

  methods: {
    toggleChat() {
      this.isOpen = !this.isOpen
    },

    handleEnter(event) {
      if (!event.shiftKey) {
        this.sendMessage()
      }
    },

    async sendMessage() {
      if (!this.userInput.trim()) return

      // 添加用户消息
      const userMessage = {
        role: 'user',
        content: this.userInput.trim()
      }
      this.messages.push(userMessage)
      this.chatHistory.push(userMessage)
      this.userInput = ''

      // 添加加载指示器
      const loadingMessage = {
        role: 'assistant',
        content: 'AI正在思考...'
      }
      this.messages.push(loadingMessage)

      try {
        const response = await fetch(this.apiUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            model: 'qwen2.5-coder:32b',
            messages: this.chatHistory,
            stream: false
          })
        })

        if (!response.ok) {
          throw new Error(`HTTP错误! 状态码: ${response.status}`)
        }

        const data = await response.json()

        // 移除加载指示器
        this.messages.pop()

        if (data.message?.content) {
          const botMessage = {
            role: 'assistant',
            content: data.message.content
          }
          this.messages.push(botMessage)
          this.chatHistory.push(botMessage)
        } else {
          throw new Error('无效的响应数据')
        }

      } catch (error) {
        console.error('错误:', error)
        // 移除加载指示器
        this.messages.pop()
        // 添加错误消息
        this.messages.push({
          role: 'assistant',
          content: '抱歉，发生了错误，请稍后重试。'
        })
      }

      // 滚动到底部
      this.$nextTick(() => {
        const container = this.$refs.messageContainer
        container.scrollTop = container.scrollHeight
      })
    }
  }
}
</script>

<style scoped>
.ai-chat-container {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.ai-chat-widget {
  position: fixed;
  bottom: 80px;
  right: 20px;
  width: 350px;
  height: 500px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0,0,0,0.1);
  display: flex;
  flex-direction: column;
  z-index: 1000;
}

.chat-header {
  padding: 15px;
  background: #4F8BF9;
  color: white;
  border-radius: 10px 10px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-title {
  font-weight: bold;
}

.minimize-btn {
  cursor: pointer;
  padding: 0 5px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
}

.message {
  margin-bottom: 10px;
  padding: 10px;
  border-radius: 10px;
  max-width: 80%;
  word-wrap: break-word;
}

.message.user {
  background: #E3F2FD;
  margin-left: auto;
}

.message.bot {
  background: #F5F5F5;
}

.chat-input {
  padding: 15px;
  border-top: 1px solid #eee;
  display: flex;
  gap: 10px;
}

.chat-input textarea {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 5px;
  resize: none;
  font-family: inherit;
}

.chat-input button {
  padding: 8px 15px;
  background: #4F8BF9;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.chat-input button:hover {
  background: #3D7BE7;
}

.chat-launcher {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 50px;
  height: 50px;
  background: #4F8BF9;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 2px 5px rgba(0,0,0,0.2);
  z-index: 1000;
}

.launcher-icon {
  font-size: 24px;
}
</style> 